﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Data.OleDb;
using ProtekUtil;
using System.Data.Odbc;

namespace DIProject.Util
{
    public class File
    {
        public static Int32 FilesMinusDey
        {
            get
            {
                try
                {
                    return Properties.Settings.Default.FilesMinusDey;
                }
                catch (Exception ee)
                {
                    return 30;
                }
            }
        }
        private static void RenameDbfFiles(string directory)
        {
            if (!Directory.Exists(directory))
                throw new Util.DIException("Не правильно задана директория с *.dbf файлами");
            string[] result = Directory.GetFiles(directory, "*.dbf", SearchOption.TopDirectoryOnly);
            foreach (string fn in result)
            {                
                if (Path.GetFileName(fn).Length > 12)
                {
                    RenameFile(fn);
                }
            }
        }
        private static void RenameFile(string fileName)
        {
            Int32 l = fileName.Length;
            if (l < 8)
                return;
            //Int32 index = fileName.Length - 9;
            l -= 9;
            string newFileName = fileName.Substring(l);
            try
            {
                string directory = Path.GetDirectoryName(fileName);
                string newFilePath = Path.Combine(directory, newFileName);
                System.IO.File.Move(fileName, newFilePath);
                System.IO.File.Delete(fileName);
                
            }
            catch (IOException ioe)
            {
                string s = ioe.ToString();
                System.Windows.Forms.MessageBox.Show(s);
                throw ioe;
            }
            catch (Exception ee)
            {
                string s = ee.ToString();
                System.Windows.Forms.MessageBox.Show(s);
                throw ee;
            }
            
        }
        public static string[] GetDBFFiles(string directory)
        {
            List<string> r = new List<string>();
            DateTime toDey = DateTime.Now.AddDays(System.Convert.ToDouble(FilesMinusDey) * -1);
            if (!Directory.Exists(directory))
                throw new Util.DIException("Не правильно задана директория с *.dbf файлами");
            RenameDbfFiles(directory);
            string[] result = Directory.GetFiles(directory, "*.dbf", SearchOption.TopDirectoryOnly);            
           // string[] result2 = new string[result.Length];
            for (Int32 i=0;i<result.Length;i++)
            {
                string fn = result[i];
                if (System.IO.File.GetLastWriteTime(fn) < toDey)
                    continue;
                r.Add(Path.GetFileName(fn));
            }
            return r.ToArray();
        }
        public static string[] GetSSTFiles(string directory)
        {
            if (!Directory.Exists(directory))
                throw new Util.DIException("Не правильно зада директория с *.sst файлами");
            string[] result = Directory.GetFiles(directory, "*", SearchOption.TopDirectoryOnly);
            System.Text.RegularExpressions.Regex reSSTFile = new System.Text.RegularExpressions.Regex("^(?<fileName>\\d+\\.\\d+)\\s*",System.Text.RegularExpressions.RegexOptions.IgnoreCase|System.Text.RegularExpressions.RegexOptions.Multiline);
            System.Collections.Generic.List<string> res = new List<string>();
            for (Int32 i=0;i<result.Length;i++)
            {
                string s = Path.GetFileName(result[i]);
                if(reSSTFile.IsMatch(s))
                    res.Add(s);
            }
            return res.ToArray();
        }
        public static string[] GetSSTFiles1(string directory)
        {
            if (!Directory.Exists(directory))
                throw new Util.DIException("Не правильно зада директория с *.sst файлами");
            string[] result = Directory.GetFiles(directory, "*.sst", SearchOption.TopDirectoryOnly);
           // System.Text.RegularExpressions.Regex reSSTFile = new System.Text.RegularExpressions.Regex("^(?<fileName>\\d+\\.sst)\\s*", System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Multiline);
            System.Collections.Generic.List<string> res = new List<string>();
            for (Int32 i = 0; i < result.Length; i++)
            {
                string s = Path.GetFileName(result[i]);
              //  if (reSSTFile.IsMatch(s))
                    res.Add(s);
            }
            return res.ToArray();
        }
        /// <summary>
        /// инфа по накладным протека
        /// </summary>
        /// <param name="path"></param>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public static ReceptionGoods.WaybillInfo GetWaybillInfoProtek(string path, string tableName)
        {
            ReceptionGoods.WaybillInfo wi = new DIProject.ReceptionGoods.WaybillInfo();
            if (System.IO.File.Exists(path + "/" + tableName))
            {
                System.IO.FileInfo fi = new FileInfo(path + "/" + tableName);
                wi.DateWaybill = fi.CreationTime;
                wi.NumWayBill = tableName;
                wi.TableName = tableName;
            }
            return wi;
        }
        /// <summary>
        /// инфа по доклодным формата аптеки 2002
        /// </summary>
        /// <param name="path"></param>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public static ReceptionGoods.WaybillInfo GetWaybillInfoApteka2002(string path, string tableName)
        {
            ReceptionGoods.WaybillInfo wi = new DIProject.ReceptionGoods.WaybillInfo();
            string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
               + path + ";Extended Properties=dBASE IV;User ID=Admin;Password=";
            string QueryString = "SELECT NDOC, DATEDOC FROM " + tableName;
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                try
                {
                    OleDbCommand command = new OleDbCommand(QueryString, connection);
                    connection.Open();
                    OleDbDataReader rd = command.ExecuteReader();                    
                    wi.TableName = tableName;
                    if (rd.Read())
                    {
                        if (!rd.IsDBNull(0))
                        {
                             object obj = rd[0].GetType();
                            wi.NumWayBill = rd.GetString(0);
                        }
                        if (!rd.IsDBNull(1))
                        {
                             object obj = rd[1];
                            wi.DateWaybill = rd.GetDateTime(1);
                        }
                    }
                    return wi;
                }
                catch (OleDbException odexc)
                {
                    throw new DIException("Невозможно прочитать накладную! " + tableName, odexc);
                }
                catch (Exception exc)
                {
                    throw new DIException("Невозможно прочитать накладную! " + tableName, exc);
                }
            }
        }
        public static ReceptionGoods.WaybillInfo GetWaybillInfoCia(string path, string tableName)
        {
            string tmp1 = string.Empty;
            if (tableName.EndsWith(".dbf"))
            {
                tmp1 = tableName.Substring(0, tableName.Length - 4);
            }
            else
            {
                tmp1 = tableName;
            }
            string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
               + path + ";Extended Properties=dBASE IV;User ID=Admin;Password=";
            string QueryString = "select DCODE,DATE_DOC from " + tmp1;
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                try
                {
                    OleDbCommand command = new OleDbCommand(QueryString, connection);
                    connection.Open();
                    OleDbDataReader rd = command.ExecuteReader();
                    ReceptionGoods.WaybillInfo wi = new DIProject.ReceptionGoods.WaybillInfo();
                    wi.TableName = tableName;
                    if (rd.Read())
                    {
                        if (!rd.IsDBNull(0))
                        {
                            // object obj = rd[0].GetType();
                            wi.NumWayBill = rd.GetString(0);//.ToString();
                        }
                        if (!rd.IsDBNull(1))
                        {
                            // object obj = rd[1];
                            string tmp = rd.GetString(1);
                            DateTime dt;
                            if (DateTime.TryParse(tmp, out dt))
                            {
                                wi.DateWaybill = dt;
                            }
                            else
                            {
                                wi.DateWaybill = DateTime.Now;
                            }
                           // wi.DateWaybill = rd.GetDateTime(1);
                        }
                    }
                    return wi;
                }
                catch (OleDbException odexc)
                {
                    throw new DIException("Невозможно прочитать накладную! " + tableName, odexc);
                }
                catch (Exception exc)
                {
                    throw new DIException("Невозможно прочитать накладную! " + tableName, exc);
                }
            }
        }
        public static ReceptionGoods.WaybillInfo GetWaybillInfo(string path, string tableName)
        {
            string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
               + path + ";Extended Properties=dBASE IV;User ID=Admin;Password=";
            string QueryString = "select NUMNAK,DATAGOT from " + tableName;
            using (OleDbConnection connection = new OleDbConnection(connectionString))            
            {
                try
                {
                    OleDbCommand command = new OleDbCommand(QueryString, connection);
                    connection.Open();
                    OleDbDataReader rd = command.ExecuteReader();
                    ReceptionGoods.WaybillInfo wi = new DIProject.ReceptionGoods.WaybillInfo();
                    wi.TableName = tableName;
                    if (rd.Read())
                    {
                        if (!rd.IsDBNull(0))
                        {
                           // object obj = rd[0].GetType();
                            wi.NumWayBill = rd.GetDouble(0).ToString();
                        }
                        if (!rd.IsDBNull(1))
                        {
                           // object obj = rd[1];
                            wi.DateWaybill = rd.GetDateTime(1);
                        }
                    }
                    return wi;
                }
                catch (OleDbException odexc)
                {
                    throw new DIException("Невозможно прочитать накладную! " + tableName, odexc);
                }
                catch (Exception exc)
                {
                    throw new DIException("Невозможно прочитать накладную! " + tableName, exc);
                }
            }
            //return null;
            
        }
        public static DataSets.waybillsData.MoronDataTable GetCIAData(string path, string tableName)
        {
            string QueryString = 
@"SELECT CODE, KOLVO, PRICE_OPL, 
SUM_BASE,NDS_PR, 
NDS_SUM, SUM_OPL, NSP, 
PRICE_BASE, 
PRO, PRO_NNDS, PRO_PR, 
NC_IMP_PR, NC_IMP_SUM, NC_OPT_PR, NC_OPT_SUM, 
PRICE_OPT, PRICE_REES, DATE_REES, SERIES, 
WEIGHT, DCODE, DATE_DOC, GTD, ID, 
SERT_N, ID_APTEKA, ID_FILIAL, PRICE_O, 
XCONCEPT, TAM_PER, TAM_SUM, PRODUCT, 
PRODUCER, SROK_S, NSP_PR, EAN13, 
FARMCODE, SE_NUM, SE_ORG, SE_SROK
FROM " + tableName; ;
            string connectionString1 =
@"CollatingSequence=ASCII;DBQ=" + path + ";DefaultDir=" + path + ";" +
"Deleted=0;Driver={Microsoft dBase Driver (*.dbf)};FIL=dBase 5.0;MaxBufferSize=2048;" +
"MaxScanRows=8;PageTimeout=5;SafeTransactions=0;Statistics=0;Threads=3;UID=admin;";
            DataSets.waybillsData.CIADataTable data = new DIProject.DataSets.waybillsData.CIADataTable();
            using (OdbcConnection connection = new OdbcConnection(connectionString1))
            {
                try
                {
                    OdbcCommand command = new OdbcCommand(QueryString, connection);
                    OdbcDataAdapter adapter = new OdbcDataAdapter(command);
                    adapter.Fill(data);
                }
                catch (OleDbException odexc)
                {
                    throw new DIException("Невозможно прочитать накладную! " + tableName, odexc);
                }
                catch (Exception exc)
                {
                    throw new DIException("Невозможно прочитать накладную! " + tableName, exc);
                }
            }
            DataSets.waybillsData.MoronDataTable result = new DIProject.DataSets.waybillsData.MoronDataTable();
            System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex("(?<prod>[^(]+)\\((?<country>\\w*)\\)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            foreach (DataSets.waybillsData.CIARow ci in data.Rows)
            {
                DataSets.waybillsData.MoronRow mr = result.NewMoronRow();
                if (!ci.IsDCODENull())
                    mr.NUMNAK = ci.DCODE;
                if (!ci.IsDATE_DOCNull())
                {
                    string tmp = ci.DATE_DOC;
                    DateTime dt;
                    if (DateTime.TryParse(tmp, out dt))
                    {
                        mr.DATAGOT = dt;
                    }
                }
                if(!ci.IsDCODENull())
                    mr.KODNLKLEK = ci.CODE;
                if(!ci.IsEAN13Null())
                    mr.EAN13 = ci.EAN13;
                if(!ci.IsPRICE_BASENull())
                    mr.CENAPRBNDS = ci.PRICE_BASE;
                if(!ci.IsPRICE_OPLNull())
                    mr.CENAPROD = ci.PRICE_OPL;
                
                mr.COUNT = ci.KOLVO;
                if(!ci.IsSERIESNull())
                    mr.SERIJ = ci.SERIES;
                if (!ci.IsSROK_SNull())
                {
                    string tmp = ci.SROK_S;
                    DateTime dt;
                    if(DateTime.TryParse(tmp,out dt))
                    {
                        mr.SROKGOD = dt;
                    }
                }
                if (!ci.IsPRODUCTNull())
                {
                    string str = ci.PRODUCT;
                    str = str.Replace("@", string.Empty);
                    str = str.Replace("#", string.Empty);
                    mr.NAMLEK = str;
                }
                string strana = string.Empty;
                string zavod = string.Empty;
                string ZavodStrana = ci.PRODUCER;
                if (!string.IsNullOrEmpty(ZavodStrana))
                {
                    System.Text.RegularExpressions.Match m = re.Match(ZavodStrana);
                    if (m != null)
                    {
                        strana = m.Groups["country"].Value;
                        zavod = m.Groups["prod"].Value;
                    }
                }
                mr.NAMSTRANA = strana;
                mr.NAMZAVOD = zavod;
                if(!ci.IsNDS_PRNull())
                    mr.PRCNDS = ci.NDS_PR;
                if(!ci.IsPRICE_REESNull())
                    mr.CENAREE = ci.PRICE_REES;
                if (!ci.IsDATE_REESNull())
                {
                    string tmp = ci.DATE_REES;
                    DateTime dt;
                    if(DateTime.TryParse(tmp,out dt))
                    {
                        mr.DATAREE = dt;
                    }
                }
                if(!ci.IsGTDNull())
                    mr.NUMDECLARE = ci.GTD;
                if(!ci.IsSE_NUMNull())
                    mr.NUMBER = ci.SE_NUM;
                if (!ci.IsSE_SROKNull())
                {
                    string tmp = ci.SE_SROK;
                    DateTime dt;
                    if (DateTime.TryParse(tmp, out dt))
                    {
                        mr.SROK = dt;
                    }
                }
                if(!ci.IsSE_ORGNull())
                    mr.NAMEPRINT = ci.SE_ORG;
                if(!ci.IsSUM_BASENull())
                    mr.SUMBNDS = ci.SUM_BASE;
                if(!ci.IsNC_IMP_PRNull())
                    mr.NACIMP = ci.NC_IMP_PR;
                if(!ci.IsNC_OPT_PRNull())
                    mr.NACOPT = ci.NC_OPT_PR;
                result.Rows.Add(mr);
            }
            return result;

        }
        public static DataSets.waybillsData.MoronDataTable GetApteka2002Data(string path, string tableName)
        {
//NDOC DATEDOC CODEPST EAN13 PRICE1 PRICE2 PRICE2N	PRCIMP PRCOPT QNT	SER	GDATE DATEMADE NAME CNTR FIRM QNTPACK 
//NDS NSP GNVLS REGPRC DATEPRC NUMGTD SERTIF SERTDATE SERTORG SUMPAY SUMNDS10 SUMNDS20 SUM10 SUM20 SUM0 EXCHCODE ERATE
            string QueryString =
@"SELECT NDOC as `NUMNAK`, DATEDOC as `DATAGOT`, CODEPST as `KODNLKLEK`, EAN13, PRICE1 as `CENARAS`, 
PRICE2 as `CENAPROD`, PRICE2N as `CENAPRBNDS`, PRCIMP as `NACIMP`, PRCOPT as `NACOPT`, QNT as `COUNT`, SER as `SERIJ`, 
GDATE as `SROKGOD`, DATEMADE , NAME as `NAMLEK`, CNTR as `NAMSTRANA`, FIRM as `NAMZAVOD`, QNTPACK as `KOLUP`, NDS as `PRCNDS`, 
NSP as `PRCNSP`, GNVLS as `OBAS`, REGPRC as `CENAREE`, DATEPRC  as `DATAREE`, NUMGTD as `NUMDECLARE`, SERTIF as `NUMBER`, 
SERTDATE as `SROK`, SERTORG as `NAMEPRINT`, SUMPAY, SUMNDS10 as `NDS10`, SUMNDS20 as `NDS20`, SUM10 as `SUMNDS10`, 
SUM20 as `SUMNDS20`, SUM0 as `SUMNDS0`
FROM " + tableName;//, PODRCD as `KODAPTEK`
            string connectionString1 = 
@"CollatingSequence=ASCII;DBQ=" + path + ";DefaultDir=" + path + ";" + 
"Deleted=0;Driver={Microsoft dBase Driver (*.dbf)};FIL=dBase 5.0;MaxBufferSize=2048;" +
"MaxScanRows=8;PageTimeout=5;SafeTransactions=0;Statistics=0;Threads=3;UID=admin;";
            string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
               + path + ";Extended Properties=dBASE IV;User ID=Admin;Password=";
            DataSets.waybillsData.MoronDataTable result = new DIProject.DataSets.waybillsData.MoronDataTable();
            using (OdbcConnection connection = new OdbcConnection(connectionString1))
            {
                try
                {
                    OdbcCommand command = new OdbcCommand(QueryString, connection);
                    OdbcDataAdapter adapter = new OdbcDataAdapter(command);
                    adapter.Fill(result);
                    return result;
                    DataSets.waybillsData.MoronRow mr;
                   // mr.su
                }
                catch (OleDbException odexc)
                {
                    throw new DIException("Невозможно прочитать накладную! " + tableName, odexc);
                }
                catch (Exception exc)
                {
                    throw new DIException("Невозможно прочитать накладную! " + tableName, exc);
                }
            }
        }
        public static DataSets.waybillsData.MoronDataTable GetMoronData(string path, string tableName)
        {
            string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
               + path + ";Extended Properties=dBASE IV;User ID=Admin;Password=";
            string QueryString =
@"SELECT   NUMNAK, DATAGOT, KODAPTEK, KODPOSTAV, KODNLKLEK, EAN13, CENARAS, CENARASDOL, CENAPRBNDS, CENAPROD, COUNT, SERIJ, 
SROKGOD, PRZPROD, NAMLEK, KODSTN, KODZAVOD, NAMSTRANA, NAMZAVOD, VID, KOLUP, PRCNDS, PRCNSP, OBAS, CENAREE, DATAREE, 
CENAREC, NUMDECLARE, NUMBER, SROK, NAMEPRINT, KODORG, PRZ_PRI, SUMBNDS, NDS10, NDS20, SUMNDS10, SUMNDS20, SUMNDS0, 
NACIMP, NACOPT from " + tableName;// +".dbf";//, SUMNDSOPT, DATEMADE, SUMPAY, EXCHCODE, ERATE 
// from " +  tableName + ".dbf";
            DataSets.waybillsData.MoronDataTable result = new DIProject.DataSets.waybillsData.MoronDataTable();
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                try
                {
                    OleDbCommand command = new OleDbCommand(QueryString, connection);
                    connection.Open();
                    OleDbDataAdapter adapter = new OleDbDataAdapter(command);
                    adapter.Fill(result);
                   // OleDbDataReader read = command.ExecuteReader();
                   /* if (read.Read())
                    {
                        string s = read.GetString(0);
                    }*/
                    return result;
                }
                catch (OleDbException odexc)
                {
                    throw new DIException("Невозможно прочитать накладную! " + tableName, odexc);
                }
                catch (Exception exc)
                {
                    throw new DIException("Невозможно прочитать накладную! " + tableName, exc);
                }
            }
            //return null;
        }
        
        public static DataSets.waybillsData.MoronDataTable GetProtekData(string path, string tableName)
        {
            DataSets.waybillsData.MoronDataTable result = new DIProject.DataSets.waybillsData.MoronDataTable();
            ProtekUtil.ProtekLoader pl = new ProtekLoader();
            pl.DataFilePath = path + "/" + tableName;
            pl.Load();
            Integration.NkldHeader head = pl.Nkld.Header;
            double numNac;
            string str = head.NDOC;
            str = str.Replace('/', '.');
            if (!double.TryParse(str,System.Globalization.NumberStyles.Float,System.Globalization.CultureInfo.InvariantCulture, out numNac))
            {
                throw new Util.DIException("Не удалось импортировать накладную");
            }
            DateTime dateDoc = head.DATEDOC;
            #region создание таблицы
            foreach (Integration.NkldItemInfo nkl in pl.Nkld)
            {
                try
                {
                    DataSets.waybillsData.MoronRow mr = result.NewMoronRow();
                    mr.EAN13 = nkl.EAN13;
                    mr.NUMNAK = numNac.ToString();
                    mr.DATAGOT = dateDoc;
                    mr.KODNLKLEK = System.Convert.ToDouble(nkl.CODEPST);
                    mr.CENARAS = System.Convert.ToDouble(nkl.PRICE1);
                    mr.CENAPRBNDS = System.Convert.ToDouble(nkl.PRICE2N);
                    mr.CENAPROD = System.Convert.ToDouble(nkl.PRICE2);
                    mr.COUNT = System.Convert.ToDouble(nkl.QNT);
                    mr.SERIJ = nkl.SER;
                    mr.SROKGOD = nkl.GDATE;
                    mr.NAMLEK = nkl.NAME;
                    mr.NAMSTRANA = nkl.CNTR;
                    mr.NAMZAVOD = nkl.FIRM;
                    mr.KOLUP = System.Convert.ToDouble(nkl.QNTPACK);
                    mr.PRCNDS = System.Convert.ToDouble(nkl.NDS);
                    mr.PRCNSP = nkl.NSP;
                    mr.OBAS = System.Convert.ToDouble(nkl.GNVLS);
                    mr.CENAREE = System.Convert.ToDouble(nkl.REGPRC);
                    mr.DATAREE = nkl.DATEPRC;
                    mr.NUMDECLARE = nkl.NUMGTD;
                    mr.NUMBER = nkl.SERTIF;
                    mr.SROK = nkl.SERTDATE;
                    mr.NAMEPRINT = nkl.SERTORG;
                    //mr.KODORG = System.Convert.ToDouble(nkl. Convert
                    // mr.SUMBNDS = System.Convert.ToDouble(nkl.
                    mr.NDS10 = System.Convert.ToDouble(nkl.SUMNDS10);
                    mr.NDS20 = System.Convert.ToDouble(nkl.SUMNDS18);
                    mr.NACIMP = System.Convert.ToDouble(nkl.PRCIMP);
                    mr.NACOPT = System.Convert.ToDouble(nkl.PRCOPT);
                    result.Rows.Add(mr);
                }
                catch (Exception ee)
                {
                    System.Windows.Forms.MessageBox.Show(ee.Message);
                }
            }
            #endregion
            return result;
        }
    }
}
